<?php
/**
 * Created by PhpStorm.
 * User: caichunmin
 * 用户地址行为
 * Date: 2017/1/9
 * Time: 17:37
 */

namespace SDXApi\Controller;

use Think\Controller;

class BehaviorAddressController extends Controller
{
    protected function _initialize()
    {
        header("Access-Control-Allow-Origin: *");
    }

    public function add(){
       // $local = $this->gps_to_baidu(23.121606, 113.322521);

        //$data = $this->gps_to_address($local['latitude'], $local['longitude']);
        //print_r($data);exit;


        $uid = I('post.uid',0,'int');
        $type = I('post.type','login');
        $location = I('post.location');
        $address = I('post.address');

        $is_h5 = I('post.is_h5'); //h5
        $is_ios = I('post.is_ios'); //ios
        $is_app = I('post.is_app'); //android
        $h5_src = I('post.h5_src'); //h5 微信分享记录 H5-P H5-Q  H5-H
        $utm_source = I('post.utm_source'); //广告来源

        $share_source = I('post.share_source');  //分享来源


        $source = $share_source ? $share_source : get_source();

        if(!$uid){
            die('uid is null');
        }
        if($type != 'login' && $type!='select_address'){
            die('type is error');
        }

        if($location){
            $location = explode(',',$location);
            $latitude = trim($location['0']);
            $longitude = trim($location['1']);
            if(!$latitude || !$longitude){
                die('latitude or longitude is error');
            }
            //坐标转换
            $local = $this->gps_to_baidu($latitude, $longitude);

            $data = $this->gps_to_address($local['latitude'], $local['longitude']);
            $data['latitude'] = $local['latitude'];
            $data['longitude'] = $local['longitude'];
        }elseif($address){
            $location = address_to_gps_amap($address);
            $data = $this->gps_to_address($location['longitude'], $location['latitude']);
            $data['latitude'] = $location['longitude'];
            $data['longitude'] = $location['latitude'];
            $data['address'] = $address;
        }else{
           // returnApiError('参数有误！');
        }

        $data['source'] = $source;
        $data['uid'] = $uid;
        $data['username'] = D('Users')->get_user_username($uid);
        $data['type'] = $type;
        $data['add_time'] = time();
        $data['is_first_login'] = 0;
        $data['utm_source'] = $utm_source;
        $data['province'] = $data['province'] ? $data['province'] : '';
        $data['city'] = $data['city'] ? $data['city'] : '';
        $data['district'] = $data['district'] ? $data['district'] : '';

        $model = M();
        $model->startTrans();
        $update_state = true;

        if($type == 'login'){
            $where = array(
                'uid' => $uid,
                'type' => 'login',
                'is_first_login' => 1
            );

            $res = M('UserBehaviorAddress')->field('id,add_time,share_uid')->where($where)->find();
            if($res){
                if($res['add_time']+300 > $data['add_time'] && $res['share_uid'] == 0){
                    $data['is_first_login'] = 1;
                    $update_state = M('UserBehaviorAddress')->where(array('id' => $res['id']))->setField('is_first_login',0);

                }else{
                    $data['is_first_login'] = 0;
                }
            }else{
                $data['is_first_login'] = 1;
            }

            //记录分享链接信息
            $data['share_uid'] = I('post.share_uid',0,'int');        //分享者id
            $data['source_type'] = I('post.source_type',0,'int');       //分享类型（1：商品，2：专题，3：专辑）
            $data['title'] = I('post.title');                           //标题(来源详情)
            $data['title_id'] = I('post.title_id',0,'int');           //标题id(来源详情id)

        }
        $val = M('UserBehaviorAddress')->add($data);

        if($update_state && $val){
            $model->commit();
            returnApiSuccess('','操作成功');
        }else{
            $model->rollback();
            returnApiError('操作失败');
        }


    }

    //gps坐标转百度坐标
    protected function gps_to_baidu($longitude, $latitude){
        $url = "http://api.map.baidu.com/geoconv/v1/?coords=$latitude,$longitude&from=1&to=5&ak=".C('BAIDU_KEY');
        $get_data = file_get_contents($url);
        $Json_Data = json_decode($get_data, true);
        $data['latitude'] = $Json_Data['result']['0']['y'];
        $data['longitude'] = $Json_Data['result']['0']['x'];
        return $data;
    }

    //地址转坐标
    protected function gps_to_address($longitude, $latitude, $coord_type=''){
        $url =C('BAIDU_URL')."ak=".C('BAIDU_KEY')."&coordtype=$coord_type&location=".$longitude.",".$latitude."&output=json";
        $get_data = file_get_contents($url);
        $Json_Data = json_decode($get_data, true);
        $data['province'] = $Json_Data['result']['addressComponent']['province'];
        $data['city'] = $Json_Data['result']['addressComponent']['city'];
        $data['district'] = $Json_Data['result']['addressComponent']['district'];
        $data['address'] = $Json_Data['result']['formatted_address']; //详情地址
        return $data;
    }
}